package org.fujie.plugin.cloud.face.baidu.server;

import cn.hutool.core.util.EnumUtil;
import com.baidu.aip.ocr.AipOcr;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.fujie.plugin.cloud.comm.constant.ProviderConstant;
import org.fujie.plugin.cloud.comm.exception.IdCardScanException;
import org.fujie.plugin.cloud.comm.util.JsonUtil;
import org.fujie.plugin.cloud.core.model.RecognizedIdCardScanRes;
import org.fujie.plugin.cloud.face.baidu.config.BaiduConfig;
import org.fujie.plugin.cloud.face.baidu.convert.BaiduIdCardConvert;
import org.fujie.plugin.cloud.face.baidu.enumd.ResEnum;
import org.fujie.plugin.cloud.face.provider.server.ProviderService;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * @author slm
 * @description
 */
public class BaiduIdCardScanServer extends ProviderService<BaiduConfig> {

    private final AipOcr bdClient;

    public BaiduIdCardScanServer(BaiduConfig config) {
        super(config);
        AipOcr client = new AipOcr(config.getAppId(), config.getAccessKeyId(), config.getAccessKeySecret());
        client.setConnectionTimeoutInMillis(6000);
        client.setSocketTimeoutInMillis(60000);
        this.bdClient = client;
    }

    /**
     * 获取供应商标识
     *
     * @return
     */
    @Override
    public String getSupplier() {
        return ProviderConstant.BAIDU_CLOUD;
    }

    /**
     * @param frontUrl 国徽面图片网络地址
     * @author sunliming
     * @description 身份证国徽面识别
     */
    @Override
    public RecognizedIdCardScanRes recognizeIdFrontCard(String frontUrl) throws JsonProcessingException {

        JsonNode jsonNode = parseIdCard(frontUrl);

        return BaiduIdCardConvert.ofFront(jsonNode.get("words_result"));
    }

    /**
     * @param backUrl 人像面图片地址
     * @author sunliming
     * @description 身份证人像面识别
     */
    @Override
    public RecognizedIdCardScanRes recognizeIdBackCard(String backUrl) throws JsonProcessingException {
        JsonNode jsonNode = parseIdCard(backUrl);
        return BaiduIdCardConvert.ofBack(jsonNode.get("words_result"));
    }

    public JsonNode parseIdCard(String url) throws JsonProcessingException {

        JSONObject res = bdClient.basicGeneral(url, new HashMap<>());
        ObjectMapper objectMapper = JsonUtil.getObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(JsonUtil.toJsonString(res));

        String status = jsonNode.get("image_status").asText();

        ResEnum resEnum = EnumUtil.getBy(ResEnum::getStatus, status);

        if (ResEnum.NORMAL == resEnum) {
            return jsonNode;
        } else {
            throw new IdCardScanException().setMessage(resEnum.getDesc());
        }
    }
}
